#!/bin/bash

#####################################################################################################
#@date    : 2020.8.23
#@author  : LT
#@function:
#(1)packet file
#(2)read des.config file add to packet file
#(3)check dest file
######################################################################################################

#
#输入参数判断
#
if (($# != 2))
then
	echo "Usage err"
	echo "example: $0 input_file_path des_config_file_path"
	exit 1
fi


file_version=0
file_commit_info=""
bak=$IFS 
IFS=$'\n'

for txt in `cat $2`
do
	if [[ -n $(echo $txt | grep "version:") ]]
	then
		#echo ${txt#*version:*v}
		result=${txt#*version:*v}
		#echo $result

		subresult_right=$result
		#for ((index=0; index<${#result}; index++))
		for ((index=0; index<4; index++))
		do
			#echo ${result:$index:1}
			subresult_left=${subresult_right%%.*}
			subresult_right=${subresult_right#*.}
			#echo $subresult_left
			#echo $((10#${subresult_left}))
			file_version=$(($file_version<<8))
			file_version=$(($file_version+$((10#${subresult_left}))))
		done
	elif [[ -n $(echo $txt | grep "commit:") ]]
	then
		#echo ${txt#*commit:}
		file_commit_info=${txt#*commit:}
		if [[ ${#file_commit_info}>128 ]]
		then
			file_commit_info=${file_commit_info:0:127}
		fi
		file_commit_info=${file_commit_info//' '/'_'}
	fi
done

IFS=$bak

#echo $file_version
#echo $file_commit_info


mkdir -p ./tmp_log
#
#将当前的时间打印到log文件中
#
echo "---------------------------------------------START---------------------------------------" >> ./tmp_log/tmp.packet_mcu.log
date >> ./tmp_log/tmp.packet_mcu.log

#
#执行packet_mcu操作
#-i 源文件 -v 文件版本 -c 描述信息
#-o目标文件,为可选参数，默认为./dest.bin
#
#./bin/packet_mcu_file -i b.bin -c des.config -o ./dest.bin >> ./tmp_log/tmp.packet_mcu.log
./bin/packet_mcu_file -i $1 -v $file_version -m $file_commit_info -o ./dest.bin >> ./tmp_log/tmp.packet_mcu.log 2>&1

#
#检查执行结果，如果返回错误值，则删除目标文件
#
if (($? != 0))
then
	rm -rf ./dest.bin
	echo "目标文件生成失败，删除目标文件！" >> ./tmp_log/tmp.packet_mcu.log
	exit 1
else
	echo "目标文件生成成功！" >> ./tmp_log/tmp.packet_mcu.log
fi

#
#校验生成的目标文件
#
./bin/check_mcu_file -i ./dest.bin >> ./tmp_log/tmp.packet_mcu.log 2>&1
#
#检查执行结果，如果返回错误值，则删除目标文件
#
if (($? != 0))
then
	rm -rf ./dest.bin
	echo "目标文件校验失败，删除目标文件！" >> ./tmp_log/tmp.packet_mcu.log
	exit 1
else
	echo "目标文件校验成功！" >> ./tmp_log/tmp.packet_mcu.log
fi

echo "----------------------------------------------END---------------------------------------" >> ./tmp_log/tmp.packet_mcu.log
